import { useEffect, useState } from 'react'
import { getSupplierList } from '@/api/supplier'
export interface IUserPremissSupplier {
  supplierId: number
  supplierName: string
}
const useSearchSupplier = (code: 'supplierCode' | 'supplierId' = 'supplierCode') => {
  useEffect(() => {
    handleSearchSupplier()
  }, [])
  let SupplierTimeoutA: ITimeoutType
  const [SupplierOption, setSupplierOption] = useState<IOptionItem[]>([])
  const handleSearchSupplier = (newValue = '') => {
    if (SupplierTimeoutA) {
      clearTimeout(SupplierTimeoutA)
      SupplierTimeoutA = null
    }
    const getOptions = async () => {
      const res = await getSupplierList<{
        supplierName: string
        supplierCode: string
        supplierId: string
        firstOrderMustQuotation: 0 | 1
        reorderMustQuotation: 0 | 1
      }>({
        keyword: newValue,
        useStatus: 1,
      })
      if (res.code === 200) {
        const SupplierOption =
          res?.data?.list?.map((item) => {
            return {
              label: item.supplierName,
              value: item[code],
              firstOrderMustQuotation: item.firstOrderMustQuotation,
              reorderMustQuotation: item.reorderMustQuotation,
            }
          }) || []
        setSupplierOption([...SupplierOption])
      }
    }
    SupplierTimeoutA = setTimeout(getOptions, 500)
  }
  return { SupplierOption, setSupplierOption, handleSearchSupplier }
}

export default useSearchSupplier
